﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ShopPowerTemplate.Entities;
using Windows.UI.Notifications;
using ShopPowerTemplate.WebServiceReference;
using Windows.UI.Xaml.Media.Imaging;

namespace ShopPowerTemplate.Common
{
    public class TilesHelper
    {
        public static async void UpdateTile()
        {
            WebServiceClient service = new WebServiceClient();
            var itemsToTiles = (await service.GetProminentProductsAsync()).Take(5).ToList();

            if (itemsToTiles.Count > 0)
            {
                TileUpdater updater = Windows.UI.Notifications.TileUpdateManager.CreateTileUpdaterForApplication();
                if (updater != null && updater.Setting == NotificationSetting.Enabled)
                {
                    updater.EnableNotificationQueue(true);

                    foreach (Product item in itemsToTiles)
                        PublishImageWithTitleTile(item, itemsToTiles.IndexOf(item));
                }
            }
        }

        private async static void PublishImageWithTitleTile(Product item, int itemIndex)
        {
            //Retrieve product info
            WebServiceClient service = new WebServiceClient();
            Image productImage = await service.GetProductFirstImageAsync(item.Id);
            string tileImage = null;
            if (productImage != null)
                tileImage = await ZipHelper.ExtractToLocalStore(productImage.Data, "tile" + itemIndex.ToString());
            if (tileImage == null)
                tileImage = "/Assets/noimage.png";

            //Wide
            var wideTile = Windows.UI.Notifications.TileUpdateManager.GetTemplateContent(Windows.UI.Notifications.TileTemplateType.TileWideImageAndText01);
            var wideText = wideTile.GetElementsByTagName("text");
            var wideImage = wideTile.GetElementsByTagName("image");
            wideText[0].AppendChild(wideTile.CreateTextNode(item.Name));
            wideImage[0].Attributes[1].NodeValue = tileImage;

            //Square
            var squareTile = Windows.UI.Notifications.TileUpdateManager.GetTemplateContent(Windows.UI.Notifications.TileTemplateType.TileSquareImage);
            var squareImage = squareTile.GetElementsByTagName("image");
            squareImage[0].Attributes[1].NodeValue = tileImage;

            var node = wideTile.ImportNode(squareTile.GetElementsByTagName("binding").Item(0), true);
            wideTile.GetElementsByTagName("visual").Item(0).AppendChild(node);

            var tileNotification = new Windows.UI.Notifications.TileNotification(wideTile);
            Windows.UI.Notifications.TileUpdateManager.CreateTileUpdaterForApplication().Update(tileNotification);
        }
    }
}
